#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>

#include "cmd.h"
#include "parse.h"


void read_line(char *line, int size)
{
	fgets(line, size, stdin);
	line[strlen(line) - 1] = '\0';	
}

int main()
{
	char buffer[1024];
	struct cmd args[MAX_CMDC];
	int cmdc, i;
	
    while (1) {
    	for (i = 0; i < MAX_CMDC; ++i) {
    		args[i].argc = 0;
    		args[i].input = NULL;
    		args[i].output = NULL;
		}
    	printf("shell> ");
	//fflush(stdout);
    	read_line(buffer, 1024);
	//printf("%s\n", buffer);
    	cmdc = parse_pipe_cmd(buffer, args);
        dump_pipe_cmd(cmdc, args);
	if (builtin_cmd(args)) {
		continue;
	}
	pid_t pid = fork();
	if (pid == 0) {
	       	exec_pipe_cmd(cmdc, args);
	}
	wait(NULL);
	for (i = 0; i < cmdc; ++i) {
		if (args[i].input != NULL) 
			free(args[i].input);
		if (args[i].output !=NULL) 
			free(args[i].output);
	}
    }
    return 0;
}
